import { Node, Vec3 } from "cc";
import { ecs } from "db://app-game/libs/ecs/ECS";
import { ECSEntity } from "db://app-game/libs/ecs/ECSEntity";
import { BaseMonsters } from "../../../common/db/db-level/DBLevel.type";
import { LittleMonster } from "../../../ecs/little-monster/LittleMonster";
import { Level } from "../Level";
import { LevelBaseModelComp } from "../model/LevelBaseModelComp";
import { MonsterFactoryComp } from "../model/MonsterFactoryComp";

/** 怪兽工厂组件 */
@ecs.register("MonsterFactory")
export class MonsterFactorySystem
  extends ecs.ComblockSystem
  implements ecs.IEntityEnterSystem, ecs.ISystemUpdate
{
  filter(): ecs.IMatcher {
    return ecs.allOf(MonsterFactoryComp, LevelBaseModelComp);
  }

  entityEnter(level: Level): void {
    this.initialize(level);
  }
  update(entity: ECSEntity, dt: number): void {}

  /** 初始化地图怪物生成 */
  initialize(level: Level) {
    // 1.初始化生成基础怪物
    const { data } = level.LevelBaseModel;
    const { node, activeMonsters } = level.MonsterFactory;
    data.baseMonsters.forEach((item) => {
      for (let i = 0; i < item.baseCount; ++i) {
        const monster = this.createMonster(item, node);
        activeMonsters.set(monster.eid, monster);
      }
    });
  }

  /** 创建怪兽 */
  createMonster(res: BaseMonsters, parent: Node): LittleMonster {
    const { monsterId, spawnArea } = res;
    // 1.校验是否生成是否满足条件
    // 2.调整全局难度
    // 3.天气影响
    // 4.创建怪物实例
    const monster = ecs.getEntity<LittleMonster>(LittleMonster);
    const pos = this.calculateSpawnPosition(spawnArea);
    const params = { id: monsterId, parent, initPos: pos };
    monster.load(params);

    return monster;
  }

  /** 计算怪兽生成位置 */
  calculateSpawnPosition(area: {
    center: {
      x: number;
      y: number;
      z: number;
    };
    radius: number;
  }): Vec3 {
    return new Vec3(
      area.center.x + (Math.random() * 2 - 1) * area.radius,
      area.center.y + (Math.random() * 2 - 1) * area.radius,
      0
    );
  }
}
